<template>
  <div class="intelligent-qa">
    <!-- 聊天头部 -->
    <header class="bg-white border-b sticky top-0 z-10">
      <div class="container mx-auto px-4 py-3">
        <div class="flex justify-between items-center">
          <div class="flex items-center">
            <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mr-3">
              <i class="fas fa-robot text-blue-600"></i>
            </div>
            <div>
              <h1 class="text-lg font-bold text-gray-800">律智助手</h1>
              <p class="text-sm text-green-600">在线 • 随时为您服务</p>
            </div>
          </div>
          <button @click="clearChat" class="text-gray-500 hover:text-gray-700">
            <i class="fas fa-trash"></i>
          </button>
        </div>
      </div>
    </header>

    <!-- 聊天区域 -->
    <div class="chat-container" ref="chatContainer">
      <div class="container mx-auto px-4 py-6">
        <!-- 欢迎消息 -->
        <div v-if="messages.length === 0" class="welcome-section mb-6">
          <div class="text-center">
            <div class="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <i class="fas fa-robot text-blue-600 text-3xl"></i>
            </div>
            <h2 class="text-xl font-bold text-gray-800 mb-2">您好！我是律智助手</h2>
            <p class="text-gray-600 mb-6">我可以为您提供法律咨询、案件分析、文书起草等服务</p>
          </div>
          
          <!-- 快速问题 -->
          <div class="quick-questions">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">常见问题</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
              <button 
                v-for="question in quickQuestions" 
                :key="question.id"
                @click="askQuestion(question.text)"
                class="p-4 bg-white border border-gray-200 rounded-lg text-left hover:bg-blue-50 hover:border-blue-300 transition-colors"
              >
                <div class="flex items-start">
                  <i :class="question.icon" class="text-blue-600 mt-1 mr-3"></i>
                  <div>
                    <h4 class="font-medium text-gray-800 mb-1">{{ question.title }}</h4>
                    <p class="text-sm text-gray-600">{{ question.text }}</p>
                  </div>
                </div>
              </button>
            </div>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="messages-list space-y-4">
          <div 
            v-for="message in messages" 
            :key="message.id"
            :class="[
              'flex',
              message.isUser ? 'justify-end' : 'justify-start'
            ]"
          >
            <!-- AI消息 -->
            <div v-if="!message.isUser" class="flex items-start max-w-3xl">
              <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                <i class="fas fa-robot text-blue-600 text-sm"></i>
              </div>
              <div class="bg-white rounded-lg p-4 shadow-sm border">
                <div class="text-gray-800 leading-relaxed" v-html="formatMessage(message.content)"></div>
                <div class="text-xs text-gray-500 mt-2">{{ formatTime(message.timestamp) }}</div>
                <!-- 消息操作 -->
                <div class="flex items-center mt-3 space-x-3">
                  <button @click="copyMessage(message.content)" class="text-gray-400 hover:text-gray-600 text-xs">
                    <i class="fas fa-copy mr-1"></i>复制
                  </button>
                  <button @click="likeMessage(message)" class="text-gray-400 hover:text-green-600 text-xs">
                    <i class="fas fa-thumbs-up mr-1"></i>有用
                  </button>
                  <button @click="dislikeMessage(message)" class="text-gray-400 hover:text-red-600 text-xs">
                    <i class="fas fa-thumbs-down mr-1"></i>无用
                  </button>
                </div>
              </div>
            </div>

            <!-- 用户消息 -->
            <div v-else class="flex items-start max-w-2xl">
              <div class="bg-blue-600 text-white rounded-lg p-4 mr-3">
                <div class="leading-relaxed">{{ message.content }}</div>
                <div class="text-xs text-blue-100 mt-2">{{ formatTime(message.timestamp) }}</div>
              </div>
              <div class="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center flex-shrink-0">
                <i class="fas fa-user text-gray-600 text-sm"></i>
              </div>
            </div>
          </div>

          <!-- 正在输入指示器 -->
          <div v-if="isTyping" class="flex justify-start">
            <div class="flex items-start max-w-3xl">
              <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                <i class="fas fa-robot text-blue-600 text-sm"></i>
              </div>
              <div class="bg-white rounded-lg p-4 shadow-sm border">
                <div class="flex items-center space-x-1">
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                  <span class="text-sm text-gray-500 ml-2">正在思考...</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area bg-white border-t sticky bottom-0">
      <div class="container mx-auto px-4 py-4">
        <form @submit.prevent="sendMessage" class="flex items-end space-x-3">
          <div class="flex-1 relative">
            <textarea 
              v-model="newMessage" 
              ref="messageInput"
              rows="1"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入您的法律问题..."
              @keydown="handleKeydown"
              :disabled="isTyping"
            ></textarea>
            <!-- 输入提示 -->
            <div class="absolute bottom-1 right-2 text-xs text-gray-400">
              Enter发送，Shift+Enter换行
            </div>
          </div>
          
          <button 
            type="submit" 
            :disabled="!newMessage.trim() || isTyping"
            :class="[
              'px-6 py-3 rounded-lg font-medium transition-colors',
              !newMessage.trim() || isTyping
                ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                : 'bg-blue-600 text-white hover:bg-blue-700'
            ]"
          >
            <i class="fas fa-paper-plane"></i>
          </button>
        </form>
        
        <!-- 工具栏 -->
        <div class="flex justify-between items-center mt-3 text-sm text-gray-500">
          <div class="flex items-center space-x-4">
            <span>💡 支持法律咨询、案件分析、文书起草等服务</span>
          </div>
          <div class="flex items-center space-x-2">
            <span>{{ messages.filter(m => !m.isUser).length }} 条回复</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, nextTick, onMounted } from 'vue'
import dayjs from 'dayjs'

export default {
  name: 'IntelligentQA',
  setup() {
    const messages = ref([])
    const newMessage = ref('')
    const isTyping = ref(false)
    const chatContainer = ref(null)
    const messageInput = ref(null)
    
    // 快速问题
    const quickQuestions = ref([
      {
        id: 1,
        title: '交通事故赔偿',
        text: '交通事故后如何申请赔偿？需要准备哪些材料？',
        icon: 'fas fa-car-crash'
      },
      {
        id: 2,
        title: '劳动纠纷',
        text: '被公司无故辞退，我应该如何维权？',
        icon: 'fas fa-briefcase'
      },
      {
        id: 3,
        title: '合同纠纷',
        text: '签订合同后对方违约，我可以要求哪些赔偿？',
        icon: 'fas fa-file-contract'
      },
      {
        id: 4,
        title: '房产纠纷',
        text: '买房后发现房屋质量问题，如何处理？',
        icon: 'fas fa-home'
      },
      {
        id: 5,
        title: '医疗纠纷',
        text: '医疗事故鉴定程序是怎样的？',
        icon: 'fas fa-stethoscope'
      },
      {
        id: 6,
        title: '婚姻家庭',
        text: '离婚时子女抚养权和财产如何分割？',
        icon: 'fas fa-heart'
      }
    ])
    
    // 发送消息
    const sendMessage = async () => {
      if (!newMessage.value.trim() || isTyping.value) return
      
      // 添加用户消息
      const userMessage = {
        id: Date.now(),
        content: newMessage.value.trim(),
        isUser: true,
        timestamp: new Date()
      }
      
      messages.value.push(userMessage)
      const question = newMessage.value.trim()
      newMessage.value = ''
      
      // 滚动到底部
      await nextTick()
      scrollToBottom()
      
      // 显示正在输入
      isTyping.value = true
      
      // 模拟AI回复
      setTimeout(() => {
        const aiResponse = generateAIResponse(question)
        const aiMessage = {
          id: Date.now() + 1,
          content: aiResponse,
          isUser: false,
          timestamp: new Date()
        }
        
        messages.value.push(aiMessage)
        isTyping.value = false
        
        nextTick(() => {
          scrollToBottom()
        })
      }, 1500 + Math.random() * 1000) // 1.5-2.5秒随机延迟
    }
    
    // 快速提问
    const askQuestion = (question) => {
      newMessage.value = question
      sendMessage()
    }
    
    // 生成AI回复
    const generateAIResponse = (question) => {
      const responses = {
        '交通事故': `
          <p><strong>交通事故赔偿流程如下：</strong></p>
          <ol>
            <li><strong>报警和就医：</strong>立即报警并及时就医，保留相关证据</li>
            <li><strong>收集材料：</strong>事故认定书、医疗费票据、误工证明等</li>
            <li><strong>协商或诉讼：</strong>与保险公司协商或通过法律途径解决</li>
          </ol>
          <p><strong>需要准备的材料：</strong></p>
          <ul>
            <li>交通事故认定书</li>
            <li>医疗费用票据</li>
            <li>误工费证明</li>
            <li>财产损失证明</li>
          </ul>
          <p>建议您咨询专业律师获得更详细的指导。</p>
        `,
        '劳动纠纷': `
          <p><strong>无故辞退的维权途径：</strong></p>
          <ol>
            <li><strong>收集证据：</strong>劳动合同、工资条、辞退通知等</li>
            <li><strong>申请劳动仲裁：</strong>向当地劳动仲裁委员会申请仲裁</li>
            <li><strong>要求赔偿：</strong>可要求经济补偿金或赔偿金</li>
          </ol>
          <p><strong>赔偿标准：</strong>按工作年限，每满一年支付一个月工资的经济补偿。</p>
          <p>时效性很重要，建议尽快采取行动。</p>
        `,
        '合同纠纷': `
          <p><strong>合同违约的救济措施：</strong></p>
          <ol>
            <li><strong>继续履行：</strong>要求对方继续履行合同义务</li>
            <li><strong>损害赔偿：</strong>要求赔偿因违约造成的损失</li>
            <li><strong>解除合同：</strong>在严重违约情况下可解除合同</li>
          </ol>
          <p><strong>可要求的赔偿：</strong></p>
          <ul>
            <li>直接损失（已发生的费用）</li>
            <li>可得利益损失（预期收益）</li>
            <li>违约金（如合同约定）</li>
          </ul>
        `
      }
      
      // 简单的关键词匹配
      for (const [keyword, response] of Object.entries(responses)) {
        if (question.includes(keyword)) {
          return response
        }
      }
      
      // 默认回复
      return `
        <p>感谢您的咨询。您提到的法律问题需要更详细的分析。</p>
        <p><strong>建议您：</strong></p>
        <ol>
          <li>详细描述具体情况和相关背景</li>
          <li>准备相关证据材料</li>
          <li>预约专业律师进行面对面咨询</li>
        </ol>
        <p>我们的律师团队会为您提供专业的法律建议。您可以通过<strong>预约服务</strong>功能安排咨询时间。</p>
      `
    }
    
    // 格式化消息内容
    const formatMessage = (content) => {
      return content.replace(/\n/g, '<br>')
    }
    
    // 格式化时间
    const formatTime = (timestamp) => {
      return dayjs(timestamp).format('HH:mm')
    }
    
    // 滚动到底部
    const scrollToBottom = () => {
      if (chatContainer.value) {
        chatContainer.value.scrollTop = chatContainer.value.scrollHeight
      }
    }
    
    // 处理键盘事件
    const handleKeydown = (event) => {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault()
        sendMessage()
      }
    }
    
    // 清空聊天
    const clearChat = () => {
      if (confirm('确定要清空聊天记录吗？')) {
        messages.value = []
      }
    }
    
    // 复制消息
    const copyMessage = (content) => {
      navigator.clipboard.writeText(content.replace(/<[^>]*>/g, ''))
      alert('已复制到剪贴板')
    }
    
    // 点赞消息
    const likeMessage = (message) => {
      message.liked = true
      alert('感谢您的反馈！')
    }
    
    // 点踩消息
    const dislikeMessage = (message) => {
      message.disliked = true
      alert('感谢您的反馈，我们会努力改进！')
    }
    
    return {
      messages,
      newMessage,
      isTyping,
      chatContainer,
      messageInput,
      quickQuestions,
      sendMessage,
      askQuestion,
      formatMessage,
      formatTime,
      handleKeydown,
      clearChat,
      copyMessage,
      likeMessage,
      dislikeMessage
    }
  }
}
</script>

<style scoped>
.intelligent-qa {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20px;
}

.welcome-section {
  max-width: 800px;
  margin: 0 auto;
}

.quick-questions {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.messages-list {
  max-width: 800px;
  margin: 0 auto;
}

.input-area {
  border-top: 1px solid #e5e7eb;
  background: white;
}

/* 滚动条样式 */
.chat-container::-webkit-scrollbar {
  width: 6px;
}

.chat-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 动画效果 */
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.animate-bounce {
  animation: bounce 1s infinite;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .messages-list {
    max-width: 100%;
  }
  
  .welcome-section {
    max-width: 100%;
  }
  
  .quick-questions {
    margin: 0 16px;
  }
}
</style> 